import datetime
import traceback

import jwt

from absl import flags, app

from coin.exchange.base.kr_rest.auth_base import AuthKey
from coin.exchange.upbit_v1.kr_rest.native_private_client import UpbitNativePrivateClient

flags.DEFINE_string("in_key_file", None, "Path of key_file which has authentication token.")

flags.DEFINE_string("out_key_file", None, "Path of key_file which has authentication token.")

FLAGS = flags.FLAGS


def main(_):
  try:
    key = AuthKey.from_file(FLAGS.in_key_file)
    nprivc = UpbitNativePrivateClient(FLAGS.in_key_file)
    auth_resp = nprivc.query_PUT_kakao_web_auth().msg

    print('Response from upbit:', auth_resp)

    jwt_dict = jwt.decode(auth_resp['access_token'], verify=False)

    new_key = AuthKey(owner=key.owner,
                      key_name="view+trade",
                      access_key=jwt_dict['api']["access_key"],
                      secret_key=jwt_dict['api']["secret_key"],
                      raw=dict(refresh_token=auth_resp["refresh_token"]),
                      generated=str(datetime.datetime.utcnow()),
                      generated_human=str(datetime.datetime.now()))
    print("Generated key:", new_key.as_json_str())

    if (key.access_key != new_key.access_key or key.secret_key != new_key.secret_key
        or key.refresh_token != new_key.refresh_token):
      if FLAGS.out_key_file is not None:
        for key_file in FLAGS.out_key_file.split(","):
          try:
            print(key_file)
            new_key.save_file(key_file)
          except Exception:
            print("failed to save to", key_file)
    else:
      print('key is not updated.')
  except Exception as exc:
    traceback.print_exc()
    raise

  return 0


if __name__ == '__main__':
  app.run(main)
